<template>
  <div>
    <el-dialog
      @closed="resetForm"
      :title="isAdd ? '新增学科' : '修改学科'"
      :visible="visible"
      @update:visible="$emit('update:visible', $event)"
      width="450px"
      :before-close="handleClose">

      <el-form ref="dataForm" :model="dataForm" label-width="80px" :rules="rules" v-model="loading">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="dataForm.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch v-model="dataForm.isFrontDisplay"></el-switch>
        </el-form-item>
        <el-form-item class="dialog-footer">
          <el-button @click="$emit('update:visible', false)">取 消</el-button>
          <el-button type="primary" @click="onConfirm">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getSubjectInfo, updateSubject, addSubject} from '@/api/subjectmanage'
export default {
  name: 'AuDialog',
  props:{
    visible: Boolean,
    subId: Number,
    isAdd: Boolean
  },
  data() {
    return {
      loading : false,
      dataForm: {
        subjectName: '',
        isFrontDisplay: true
      },
      rules: {
        subjectName: [{ required: true, trigger: 'blur'}],
        isFrontDisplay: []
      },
      subInfo: {}
    }
  },

  methods: {
    handleClose(done) {
      return done()
    },
    // 重置表单
    resetForm() {
      this.$refs.dataForm.resetFields()
    },
    // 获取学科详情
    async getDetail(id){
      this.loading = true
      const res = await getSubjectInfo(id)
      this.subInfo = res
      this.dataForm.subjectName = res.subjectName
      this.dataForm.isFrontDisplay = (res.isFrontDisplay === 1)
      this.loading = false
    },
    // 提交信息
    async onConfirm(){
      this.loading = true
      let res = ''
      if(this.isAdd){
        res = await addSubject(this.dataForm)
      }else {
        res = await updateSubject(this.subId, {
          id:this.subId,
          subjectName: this.dataForm.subjectName,
          isFrontDisplay: this.dataForm.isFrontDisplay
        })
      }
      this.loading = false
      if(res) {
        this.$message({
          message: this.isAdd ? '添加成功' :'修改成功',
          type: 'success'
        })
      }else {
        this.$message.error(this.isAdd ? '添加失败' :'修改失败')
      }
      this.$emit('success')
      this.$emit('update:visible', false)
    }
  },

  watch: {
    visible(val) {
      if(val && !this.isAdd && this.subId){
        this.getDetail(this.subId)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.article-info{
  font-size: 12px;
  color: #888;
}
.context-box{
  width: 760px;
}

.article-info{
  padding-left: 8px;
  span{
    margin-right: 8px;
  }
}
.dialog-footer{
  display: flex;
  justify-content: flex-end;
}
</style>
